package calificaciones;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;

import sistemas.sam.R;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.net.ParseException;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

public class AltaCalificacion extends Activity implements
		OnItemSelectedListener, OnClickListener {

	String respuesta;
	TextView alumno, matricula;
	JSONArray jArray = null;
	Button ordi, extra, recupera, ingresar;
	String idU, idM, idG;
	int Acalif_N = 0;
	InputStream is = null;
	StringBuilder sb = null;
	String result = null;
	String idTipos, message, Acalif_L;
	String Server;
	ProgressDialog dialog;
	String restar;

	public List<String> Lpase = new ArrayList<String>();

	private ConectarSam mAuthTask = null;
	public List<String> Lcalif = new ArrayList<String>();

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_alta__calificacion);

		link l = new link();
		Server = l.linkAltaCalif;

		ValidacionPasedeLista valida = new ValidacionPasedeLista();

		if (valida.Lcalificacion.size() > 0) {
			for (int i = 0; i < valida.Lcalificacion.size(); i++) {
				String a = "" + valida.Lcalificacion.get(i);
				Lpase.add(a);
				Log.d("NUevo Metodo Entra", "Lista " + Lpase.get(i));
			}
		} else {
			Lpase.add("");
		}

		valida.limpiar();

		alumno = (TextView) findViewById(R.id.alumno);
		matricula = (TextView) findViewById(R.id.matricula);
		Bundle bundle = getIntent().getExtras();
		alumno.setText("" + bundle.getString("nombreA"));

		matricula.setText("" + bundle.getString("matriA"));
		idU = bundle.getString("IDu");
		idM = bundle.getString("IDm");
		idG = bundle.getString("IDg");

		calificacion c = new calificacion();

		float pr = c.ChequecoAist(Lpase);

		ordi = (Button) findViewById(R.id.ordinario);
		extra = (Button) findViewById(R.id.extra);
		recupera = (Button) findViewById(R.id.recupera);
		ingresar = (Button) findViewById(R.id.btn_alta);
		ordi.setOnClickListener(this);
		extra.setOnClickListener(this);
		recupera.setOnClickListener(this);
		ingresar.setOnClickListener(this);

		Lcalif.addAll(c.calif(pr));

		if (pr < 80) {
			ordi.setEnabled(false);
		}

		ArrayAdapter<String> adaptador = new ArrayAdapter<String>(this,
				android.R.layout.simple_spinner_item, Lcalif);

		final Spinner combo = (Spinner) findViewById(R.id.calificacion);
		adaptador
				.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		combo.setAdapter(adaptador);

		combo.setOnItemSelectedListener(this);

	}

	@Override
	public void onItemSelected(AdapterView<?> arg0, View arg1, int location,
			long arg3) {
		// TODO Auto-generated method stub
		if (arg0.getId() == R.id.calificacion) {
			Acalif_L = Lcalif.get(location);

		}
	}

	@Override
	public void onNothingSelected(AdapterView<?> arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		if (v.getId() == R.id.ordinario) {
			idTipos = "" + 1;
		}
		if (v.getId() == R.id.extra) {
			idTipos = "" + 3;
		}
		if (v.getId() == R.id.recupera) {
			idTipos = "" + 2;
		}

		if (v.getId() == R.id.btn_alta) {

			mAuthTask = new ConectarSam();
			mAuthTask.execute((Void) null);

			calificacion c = new calificacion();

			Acalif_N = c.ValidadCalif(Acalif_L);

			Intent i = new Intent(this, AlumnosAltaCalif.class);

			Bundle bundle = new Bundle();
			bundle.putString("idM", idM);
			bundle.putString("idU", idU);
			bundle.putString("idG", idG);
			i.putExtras(bundle);
			startActivity(i);

		}
	}

	private void abrirDashboard(String msn) {
		// selectAsesoria.putExtra("materias", materias);
		// startActivity(selectAsesoria);
		// llenar(nombre,matricula);

		message = msn;

	}

	public class ConectarSam extends AsyncTask<Void, Void, Boolean> {
		@Override
		protected Boolean doInBackground(Void... params) {
			ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
			// http post
			nameValuePairs.add(new BasicNameValuePair("calificacion", String
					.valueOf(Acalif_L)));
			nameValuePairs.add(new BasicNameValuePair("numero", String
					.valueOf(Acalif_N)));
			nameValuePairs.add(new BasicNameValuePair("unidades_id", String
					.valueOf(idU)));
			nameValuePairs.add(new BasicNameValuePair("tipos", String
					.valueOf(idTipos)));
			nameValuePairs.add(new BasicNameValuePair("materia_id", String
					.valueOf(idM)));
			nameValuePairs.add(new BasicNameValuePair("matricula", String
					.valueOf(matricula.getText().toString())));

			try {
				HttpClient httpclient = new DefaultHttpClient();
				HttpPost httppost = new HttpPost(Server);
				Log.v("log_tag", Server);
				httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
				HttpResponse response = httpclient.execute(httppost);
				HttpEntity entity = response.getEntity();
				is = entity.getContent();
			} catch (Exception e) {
				Log.e("log_tag", " " + e.toString());
			}
			try {
				BufferedReader reader = new BufferedReader(
						new InputStreamReader(is, "iso-8859-1"), 8);
				sb = new StringBuilder();
				sb.append(reader.readLine() + "\n");

				String line = "0";
				while ((line = reader.readLine()) != null) {
					sb.append(line + "\n");
				}
				is.close();
				result = sb.toString();
				Log.v(" obtenido", result);
			} catch (Exception e) {
				Log.e("log_tag",
						"Error convirtiendo datos recibidos" + e.toString());
			}
			try {

				message = result;

				Log.d("ALTA CALIF ", "Calificacion  " + message);

			} catch (ParseException e1) {
				e1.printStackTrace();
			}

			return true;
		}

		@Override
		protected void onPostExecute(final Boolean success) {
			mAuthTask = null;
			Log.v("login_resultado", message);
			Log.v("login_resultado", success.toString());
			if (success) {

				Toast.makeText(getApplicationContext(), "" + message,
						Toast.LENGTH_LONG).show();

			}
		}

		@Override
		protected void onCancelled() {
			mAuthTask = null;
			// showProgress(false);
		}
	}

}
